package com.iims.flowable.flow.vo.request;

import cn.hutool.core.lang.Validator;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.iims.common.core.domain.entity.SysUser;
import com.iims.common.core.page.PageDomain;
import com.iims.common.utils.SecurityUtils;
import com.iims.common.utils.StringUtils;
import com.iims.flowable.common.constant.FlowableConstant;
import com.iims.flowable.flow.ObjectUtils;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.flowable.common.engine.api.query.Query;
import org.flowable.engine.history.HistoricProcessInstanceQuery;

import java.util.Date;

/**
 * 个人发起流程搜索视图
 *
 * @author fanpei
 * @date 2021/6/15 10:45
 */
@Data
public class FlowStartCCtoMeQueryVo extends PageDomain implements IBaseQueryVo<HistoricProcessInstanceQuery> {

    @ApiModelProperty(value = "流程分类:精确匹配")
    private String category;

    @ApiModelProperty("流程名称")
    private String name;

    @ApiModelProperty("创建开始时间:format = \"yyyy-MM-dd\"")
    @JsonFormat(pattern = "yyyy-MM-dd")
    private Date beginTime;

    @ApiModelProperty("创建结束时间:format = \"yyyy-MM-dd\"")
    @JsonFormat(pattern = "yyyy-MM-dd")
    private Date endTime;

    /**
     * 是否是抄送给我
     */
    @ApiModelProperty(hidden = true)
    private boolean ccToMe;


    @Override
    public Query genSearchQuery(HistoricProcessInstanceQuery query) {
        if (StringUtils.isNotEmpty(name)) {
            query = query.processInstanceNameLikeIgnoreCase(ObjectUtils.convertToLike(name));
        }

        if (StringUtils.isNotEmpty(category)) {
            query = query.processDefinitionCategory(category);
        }

        if (Validator.isNotNull(beginTime) && Validator.isNotNull(endTime)) {
            query = query.startedAfter(beginTime).startedBefore(endTime);
        }

        SysUser loginUser = SecurityUtils.getLoginUser().getUser();
        if (ccToMe) {
            query = query.involvedUser(loginUser.getUser_code(), FlowableConstant.CC);
        } else {
            query = query.startedBy(loginUser.getUser_code());
        }

        if (StringUtils.isEmpty(this.getOrderByColumn())) {
            query = query.orderByProcessInstanceStartTime().desc();
        }
        return query;
    }

    @Override
    public PageDomain selectPageDomain() {
        return this;
    }

}
